/*
 * Copyright (c) 2006, 2023, webrx.cn All rights reserved.
 *
 */

package cn.webrx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Project: jse2303 - Ex7</p>
 * <p>Powered by webrx On 2023-07-27 16:51:20</p>
 * <p>描述：<p>
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Ex12 {
    volatile int j = 0;
    int n = 0;
    AtomicInteger num = new AtomicInteger(0);

    public static void main(String[] args) {
        long ss = System.currentTimeMillis();
        var ex = new Ex12();
        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new Thread(ex::m1));
        }
        list.forEach(Thread::start);
        list.forEach(e -> {
            try {
                e.join();
            } catch (InterruptedException exc) {
                throw new RuntimeException(exc);
            }
        });
        long ee = System.currentTimeMillis();
        System.out.println(ex.n);
        System.out.println(ee - ss);
        list.clear();

        System.out.println("------------------------");
        ss = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            list.add(new Thread(ex::m2));
        }
        list.forEach(Thread::start);
        list.forEach(e -> {
            try {
                e.join();
            } catch (InterruptedException exc) {
                throw new RuntimeException(exc);
            }
        });
        ee = System.currentTimeMillis();
        System.out.println(ex.num.get());
        System.out.println(ee - ss);
        list.clear();

        System.out.println("------------------------");
        ss = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            list.add(new Thread(ex::m3));
        }
        list.forEach(Thread::start);
        list.forEach(e -> {
            try {
                e.join();
            } catch (InterruptedException exc) {
                throw new RuntimeException(exc);
            }
        });
        ee = System.currentTimeMillis();
        System.out.println(ex.j);
        System.out.println(ee - ss);
    }


    void m1() {
        for (int i = 0; i < 100000; i++) {
            synchronized (this) {
                ++n;
            }
        }
    }

    void m2() {
        for (int i = 0; i < 100000; i++) {
            num.incrementAndGet();
        }
    }

    void m3() {
        for (int i = 0; i < 100000; i++) {
            ++j;
        }
    }
}
